using Microsoft.SqlServer.Management.Sdk.Sfc;
using System;

namespace Microsoft.SqlServer.Management.SqlManagerUI.Scripting
{
	internal class FilePerObjectTarget : ScriptTarget
	{
		private ScriptedObjectCollection objectsScripted;

		private ScriptWriterFactory scriptWriterFactory;

		public override EventHandler<ObjectScriptedEventArgs> ObjectScriptedHandler
		{
			get
			{
				return new EventHandler<ObjectScriptedEventArgs>(this.OnObjectScripted);
			}
		}

		public override EventHandler ScriptingFinishedHandler
		{
			get
			{
				return new EventHandler(this.OnScriptingFinished);
			}
		}

		public FilePerObjectTarget(ScriptWriterFactory scriptWriterFactory)
		{
			if (scriptWriterFactory == null)
			{
				throw new ArgumentNullException("scriptWriterFactory");
			}
			this.scriptWriterFactory = scriptWriterFactory;
			this.objectsScripted = new ScriptedObjectCollection(new GetKeyHandler(this.GetKey));
		}

		protected virtual ScriptWriter GetScriptWriter()
		{
			return this.scriptWriterFactory.GetScriptWriter();
		}

		private void OnObjectScripted(object source, ObjectScriptedEventArgs e)
		{
			if (e == null)
			{
				throw new ArgumentNullException("e");
			}
			this.objectsScripted.AddScriptFragment(e.ObjectInfo, e.Script, e.Action);
		}

		private void OnScriptingFinished(object source, EventArgs e)
		{
			using (ScriptWriter scriptWriter = this.GetScriptWriter())
			{
				scriptWriter.WritingObject += new EventHandler<ScriptingProgressEventArgs>(base.OnWritingObject);
				foreach (ScriptContainer current in this.objectsScripted)
				{
					current.Script(scriptWriter);
				}
				this.objectsScripted.Clear();
			}
		}

		private Urn GetKey(Urn item)
		{
			string type;
			Urn result;
			if ((type = item.Type) != null && (type == "ForeignKey" || type == "Check"))
			{
				result = item.Parent;
			}
			else
			{
				result = item;
			}
			return result;
		}
	}
}
